import requests

from lxml import etree

from flask import Flask, render_template,request


def get_phone_info(phone):
    """
    获取手机号码归属地
    :param phone: 手机号码
    :return:
    """
    # 获取改地址下的信息
    url = f'https://ip138.com/mobile.asp?mobile={phone}&action=mobile'

    # 增加请求访问的链接信息
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
    }

    # 发送请求
    resource = requests.get(url=url, headers=headers)

    # 读取响应结果
    resource.encoding = 'utf-8'
    # 解析响应结果
    result = {}
    root = etree.HTML(resource.text)
    rootData = root.xpath('//tr')

    for row in rootData:
        key = row.xpath('td[1]/text()')
        value = row.xpath('td[2]//text()')
        if key:
            key = key[0].strip()
            value = ''.join(value).strip()
            result[key] = value

    return result


# 创建服务脚本方法
def createWeb():
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/seacher_phone',methods=['POST'])
    def seacher_phone():
        return render_template('index.html', result=get_phone_info(request.form.get('phone')))

    app.run(host='127.0.0.1', port=8099, debug=True)


# 使用dos框
def createDos():
    # 获取该手机号码信息
    while True:
        phone = input('输入需要查询的手机号码（按q退出）:')
        if phone == 'q':
            break
        print(get_phone_info(phone))


def main():
    createWeb()


if __name__ == '__main__':
    main()
